//
//  JBOAuthViewController.swift
//  sinaBlog
//
//  Created by jobo on 15/11/1.
//  Copyright © 2015年 jobo. All rights reserved.
//

import UIKit

import SVProgressHUD

class JBOAuthViewController: UIViewController {

    
    override func loadView() {
        super.loadView()
        
        
        
        view = webView
        
            
        webView.delegate = self
        
    }
    
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        //设置取消按钮
        navigationItem.rightBarButtonItem = UIBarButtonItem(title: "取消", style: UIBarButtonItemStyle.Plain, target: self, action: "cancelBtnClick")
        
        let request = NSURLRequest(URL: JBNetWorkTools.shareInstance.oauthURL())
        
        webView.loadRequest(request)
        
    }
    //取消按钮点击事件
    func cancelBtnClick()
    {
        dismissViewControllerAnimated(true, completion: nil)
        
        //取消正在加载
        SVProgressHUD.dismiss()
    }
    
    
    //懒加载
    lazy var webView = UIWebView()
    
    
    
    
    

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }
 
}


extension JBOAuthViewController : UIWebViewDelegate
{
    //请求指定连接
    func webView(webView: UIWebView, shouldStartLoadWithRequest request: NSURLRequest, navigationType: UIWebViewNavigationType) -> Bool
    {
        let urlString = request.URL!.absoluteString
        
        print(urlString)
        
        if !urlString.hasPrefix(JBNetWorkTools.shareInstance.redirect_uri)
        {
            return true
        }
        
        if let query = request.URL?.query
        {
        
            print(query)
            
            let codeString = "code="
            
            if query.hasPrefix(codeString)
            {
                print("点击的是授权")
                
                let queryNSString = query as NSString
                
                //截取code= 后面的值
                let code = queryNSString.substringFromIndex(codeString.characters.count)
                
                loadAccessToken(code)
            }
            else
            {
                print("点击的是取消")
            }
        }
        return false
    }
    
    func webViewDidStartLoad(webView: UIWebView) {
        SVProgressHUD.showWithStatus("加载页面......", maskType: SVProgressHUDMaskType.Clear)
    }
    func webViewDidFinishLoad(webView: UIWebView) {
        SVProgressHUD.dismiss()
    }
    
    
    /**
     调用网络工具类去加载加载access token
     - parameter code: code
     */
    func loadAccessToken(code: String) {
        
                
        JBNetWorkTools.shareInstance.loadAccessToken(code) { (result, error) -> () in
            if error != nil || result == nil {
                SVProgressHUD.showErrorWithStatus("网络不给力...", maskType: SVProgressHUDMaskType.Black)
                
                // 延迟关闭. dispatch_after 没有提示,可以拖oc的dispatch_after来修改
                dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                    self.cancelBtnClick()
                })
                
                return
            }
            
            print("result: \(result)")
            let account = JBUserAccount(dict: result!)
            
            // 保存到沙盒
            account.saveAccount()
            
            //加载用户数据
            account.loadUserInfo({ (error) -> () in
                if error != nil
                {
                    SVProgressHUD.showErrorWithStatus("加载用户数据出错", maskType: SVProgressHUDMaskType.Black)
                    
                    // 延迟关闭. dispatch_after 没有提示,可以拖oc的dispatch_after来修改
                    dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (Int64)(1 * NSEC_PER_SEC)), dispatch_get_main_queue(), { () -> Void in
                        self.cancelBtnClick()
                    })
 
                    return
                }
                
                print("加载用户信息成功")
               
                print("account:\(account)")
                
                self.cancelBtnClick()
                
                (UIApplication.sharedApplication().delegate as! AppDelegate).switchController(false)

            })
            
        }
    }






}


